package com.nas.crocus.controller;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.nas.crocus.domain.Persona;
import com.nas.crocus.exception.NotFoundException;
import com.nas.crocus.service.PersonaService;


@Controller
@RequestMapping(value = "/persona")
public class PersonaController {
    
    @Autowired
    private PersonaService personaService;
    
    @RequestMapping(method = RequestMethod.GET)
    public @ResponseBody Collection<Persona> buscarTodos() {
        Collection<Persona> personas = personaService.buscar();
        return personas;
    }

    @RequestMapping(value = "/id/{id}", method = RequestMethod.GET)
    public @ResponseBody Persona obtenerPersona(@PathVariable Long id) throws NotFoundException {
        Persona persona = personaService.buscar(id);
        if (persona == null) {
            throw new NotFoundException("Persona no encontrado");
        }
        return persona;
    }
    
    @RequestMapping(value ="/busqueda", method = RequestMethod.GET)
    public @ResponseBody Collection<Persona> buscar(@RequestParam("term") String term) {
        return personaService.buscarPorPatronApellidoNombreNumeroDocumento(term);
    }
    
    @RequestMapping(method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    public @ResponseBody Persona crear(@RequestBody Persona persona) {
        personaService.guardar(persona);
        return persona;
    }

    @RequestMapping(method = RequestMethod.PUT)
    public @ResponseBody Persona actualizar(@RequestBody Persona persona) {
        personaService.actualizar(persona);
        return persona;
    }
    
    
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NotFoundException.class)
    public @ResponseBody Map<String, String> handleException(NotFoundException ex) {
        Map<String, String> fault = new HashMap<String, String>();
        fault.put("error", ex.getMensaje());
        return fault;
    }
    
}
